/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.skatiger.jrove.tag;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.el.ELException;
import javax.el.VariableMapper;

import org.skatiger.jrove.JroveContext;
import org.skatiger.jrove.JroveException;
import org.skatiger.jrove.JroveHandler;
import org.skatiger.jrove.TagConfig;
import org.skatiger.jrove.TagHandler;
import org.skatiger.jrove.TemplateClient;
import org.skatiger.jrove.component.UIComponent;
import org.skatiger.jrove.el.VariableMapperWrapper;
import org.skatiger.jrove.tag.ui.DefineHandler;

final class UserTagHandler extends TagHandler
        implements TemplateClient {

    protected final TagAttribute[] vars;

    protected final URL location;

    protected final Map<String, JroveHandler> handlers;

    /**
     * @param config
     */
    public UserTagHandler(TagConfig config, URL location) {
        super(config);
        this.vars = this.tag.getAttributes().getAll();
        this.location = location;
        Iterator<DefineHandler> itr = this.findNextByType(DefineHandler.class);
        if (itr.hasNext()) {
            handlers = new HashMap<String, JroveHandler>();

            DefineHandler d = null;
            while (itr.hasNext()) {
                d = itr.next();
                this.handlers.put(d.getName(), d);
            }
        } else {
            handlers = null;
        }
    }

    public void apply(JroveContext ctx, UIComponent parent) throws IOException,
            JroveException, ELException {
        VariableMapper orig = ctx.getVariableMapper();

        // setup a variable map
        if (this.vars.length > 0) {
            VariableMapper varMapper = new VariableMapperWrapper(orig);
            for (int i = 0; i < this.vars.length; i++) {
                varMapper.setVariable(this.vars[i].getLocalName(),
                        this.vars[i].getValueExpression(ctx, Object.class));
            }
            ctx.setVariableMapper(varMapper);
        }

        // eval include
        try {
            ctx.pushClient(this);
            ctx.includeJrove(parent, this.location);
        } catch (FileNotFoundException e) {
            throw new TagException(this.tag, e.getMessage());
        } finally {

            // make sure we undo our changes
            ctx.popClient(this);
            ctx.setVariableMapper(orig);
        }
    }

    public boolean apply(JroveContext ctx, UIComponent parent, String name)
            throws IOException, JroveException, ELException {
        if (name != null) {
            if (this.handlers == null) {
                return false;
            }
            DefineHandler handler = (DefineHandler) this.handlers.get(name);
            if (handler != null) {
                handler.applyDefinition(ctx, parent);
                return true;
            } else {
                return false;
            }
        } else {
            this.nextHandler.apply(ctx, parent);
            return true;
        }
    }

}
